package com.second.tictactoeandroid2;

import com.example.tictactoeandroid.R;

import highscore.HighScoreDatabaseFactory;
import highscore.HighScore;
import highscore.HighScoreDatabase; 

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
import android.view.View; 

import java.io.IOException; 
import java.util.Iterator;
import java.util.Map.Entry;

public class HighScoreActivity extends Activity {
	
	private HighScoreDatabaseFactory highScoreFactory = new HighScoreDatabaseFactory();
	private HighScoreDatabase highScoreDatabase; 
	private HighScore highScoreKeeper; 

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_high_score);
		try{
			System.out.println("HighScore is being created"); 
			highScoreDatabase = highScoreFactory.newDatabase();
			highScoreKeeper = highScoreDatabase.retrieveHighScore();
			System.out.println("highscore retrieved"); 
			showHighScore(highScoreKeeper);	
		} catch(IOException e){
			new IOException("Console input outut not supported"); 
		} 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.high_score, menu);
		return true;
	}
	
	private void showHighScore(HighScore highscore){
		String playerHighScore = ""; 
		Iterator<Entry<String, Integer>> it = highscore.getMap().entrySet().iterator(); 
		while(it.hasNext()){
			Entry<String, Integer> entry = it.next(); 
			StringBuilder s = new StringBuilder(); 
			//playerHighScore = playerHighScore +  s.append(it); 
			playerHighScore = playerHighScore + s.append(entry.getKey() + " : " + s.append(entry.getValue()) + "\n");  
		}
		TextView text = (TextView)findViewById(R.id.highScores); 
		text.setText(playerHighScore);
	}
	
	
	public void addHighScore(View view){
		Intent intent = getIntent(); 
		String name = intent.getStringExtra(GameBoardActivity.USER_NAME);
		int score = intent.getIntExtra(GameBoardActivity.SCORE, 0);
		highScoreKeeper.addScore(name, score); 
		try{
			highScoreDatabase.write(highScoreKeeper); 
		}catch (IOException e){
			System.out.println("No database found");
		}
		showHighScore(highScoreKeeper); 
	}

}
